/*
 * @Descripttion   :
 * @version        :
 * @Author         :
 * @Date           : 2025-06-26 11:18
 * @LastEditTime   : 2025-06-26 11:18
 */
export default class CollisionSystem {
  constructor () {
    this.objects = []
    this.currentCollisions = new Map()
    this.lastCollisions = new Map()
  }

  addObject (object) {
    if (!this.objects.includes(object)) {
      this.objects.push(object)
    }
  }

  update () {
    this.currentCollisions.clear()

    // 检测所有碰撞
    for (let i = 0; i < this.objects.length; i++) {
      for (let j = i + 1; j < this.objects.length; j++) {
        const obj1 = this.objects[i]
        const obj2 = this.objects[j]

        if (this.checkCollision(obj1, obj2)) {
          const key = `${obj1.uuid}-${obj2.uuid}`
          this.currentCollisions.set(key, { obj1, obj2 })
        }
      }
    }

    // 处理碰撞事件
    this.handleCollisionEvents()
    this.lastCollisions = new Map(this.currentCollisions)
  }

  handleCollisionEvents () {
    // 检测新碰撞（OnCollisionEnter）
    this.currentCollisions.forEach(({ obj1, obj2 }, key) => {
      if (!this.lastCollisions.has(key)) {
        // 触发obj1的回调
        if (obj1.onCollisionEnter) obj1.onCollisionEnter(obj2)
        if (obj1.dispatchEvent) {
          obj1.dispatchEvent({
            type: 'collisionenter',
            other: obj2
          })
        }

        // 触发obj2的回调
        if (obj2.onCollisionEnter) obj2.onCollisionEnter(obj1)
        if (obj2.dispatchEvent) {
          obj2.dispatchEvent({
            type: 'collisionenter',
            other: obj1
          })
        }
      }
    })

    // 检测碰撞结束（OnCollisionExit）
    this.lastCollisions.forEach(({ obj1, obj2 }, key) => {
      if (!this.currentCollisions.has(key)) {
        // 触发obj1的回调
        if (obj1.onCollisionExit) obj1.onCollisionExit(obj2)
        if (obj1.dispatchEvent) {
          obj1.dispatchEvent({
            type: 'collisionexit',
            other: obj2
          })
        }

        // 触发obj2的回调
        if (obj2.onCollisionExit) obj2.onCollisionExit(obj1)
        if (obj2.dispatchEvent) {
          obj2.dispatchEvent({
            type: 'collisionexit',
            other: obj1
          })
        }
      }
    })
  }

  checkCollision (obj1, obj2) {
    obj1.updateMatrixWorld()
    obj2.updateMatrixWorld()
    const box1 = new GC.Box3().setFromObject(obj1)
    const box2 = new GC.Box3().setFromObject(obj2)
    return box1.intersectsBox(box2)
  }
}

// // 使用示例
// const collisionSystem = new CollisionSystem();

// const box1 = createBox(0xff0000, [0, 0, 0]);
// const box2 = createBox(0x00ff00, [1, 0, 0]);

// // 注册回调方式1：直接属性
// box1.onCollisionEnter = (other) => {
//   console.log('Box1开始碰撞:', other.name);
// };

// // 注册回调方式2：事件监听
// box2.addEventListener('collisionenter', (e) => {
//   console.log('Box2开始碰撞:', e.other.name);
// });

// collisionSystem.addObject(box1);
// collisionSystem.addObject(box2);

// function animate() {
//   collisionSystem.update();
//   requestAnimationFrame(animate);
// }
// animate();
